<template>
  <div class="product-details">
    <h3>商品详情</h3>
    <div v-if="product" class="details-container">
      <img :src="`/api/${product.image}`" alt="Product Image" />
      <div class="details-info">
        <h4>{{ product.goodsName }}</h4>
        <p>{{ product.description }}</p>
        <p class="price">价格: ¥{{ product.price.toFixed(2) }}</p>
        <BaseButton variant="info" size="small" @click="downloadImage">
          下载图片
        </BaseButton>
      </div>
    </div>
    <div v-else class="loading">
      <p>加载中...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'  // 引入 axios
import BaseButton from '../components/BaseButton.vue'

const route = useRoute()
const productId = ref(route.params.id)  // 获取路由传递的商品 id
const product = ref(null)  // 用于保存商品详情数据

// 获取商品详情
const fetchProductDetails = async () => {
  try {
    const response = await axios.get(`/api/product/detail?id=${productId.value}`)
    if (response.data.code === 0) {
      product.value = {
        goodsId: response.data.data.goodsId,
        goodsName: response.data.data.goodsName,
        description: response.data.data.description,
        price: parseFloat(response.data.data.price),
        image: response.data.data.productImage  // 设置商品图片链接
      }
    } else {
      console.error('Failed to fetch product details', response.data.message)
    }
  } catch (error) {
    console.error('Error fetching product details:', error)
  }
}

// 在组件挂载时获取商品详情
onMounted(() => {
  fetchProductDetails()
})

// 下载图片的函数
const downloadImage = async () => {
  if (!product.value || !product.value.goodsId) {
    alert("商品信息不完整！");
    return;
  }

  try {
    // 发送请求下载图片
    const response = await axios.get(`/api/product/downloadImage?id=${product.value.goodsId}`,{
      responseType: 'blob'
    })

    // 创建一个下载链接
    const blob = response.data
    const link = document.createElement('a')
    const url = window.URL.createObjectURL(blob)  // 创建一个指向 blob 的 URL
    link.href = url
    link.download = `${response.headers.get("content-disposition").split("filename=")[1].replace(/"/g, "")}`  // 设置下载文件的名称
    document.body.appendChild(link)
    link.click()  // 模拟点击下载链接
    document.body.removeChild(link)  // 移除链接
    // 释放对象 URL
    window.URL.revokeObjectURL(url)

  } catch (error) {
    console.log(error)
    alert("图片下载失败，请稍后再试！");
  }
}
</script>

<style scoped>
.product-details {
  padding: var(--spacing-large);
  background-color: var(--background-color);
}

.product-details h3 {
  text-align: center;
  margin-bottom: var(--spacing-large);
  color: var(--primary-color);
}

.details-container {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-large);
  background-color: var(--card-background);
  padding: var(--spacing-large);
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
}

.details-container img {
  width: 50%;
  flex: 1 1 300px;
  height: auto;
  border-radius: var(--border-radius);
}

.details-info {
  width: 600px;
  flex: 2 1 300px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  text-wrap: normal;
}

.details-info h4 {
  margin-bottom: var(--spacing-small);
  color: var(--secondary-color);
}

.details-info p {
  font-size: 16px;
  color: var(--text-color);
  margin-bottom: var(--spacing-small);
}

.price {
  font-size: var(--font-size-large);
  font-weight: bold;
  color: #e74c3c;
}

.download-button {
  margin-top: var(--spacing-small);
}

.loading {
  text-align: center;
  color: var(--text-color);
}

/* 使用 BaseButton 组件 */
.download-button {
  align-self: flex-start;
}

@media (max-width: 768px) {
  .details-container {
    flex-direction: column;
    padding: var(--spacing-base);
  }

  .details-info {
    flex: none;
  }
}
</style>
